// arch-tag: 34b3ac61-a7e2-48ed-9c2e-486135a50a78
package de.yvert.jingle.impl.writer;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;

import de.yvert.jingle.Image;
import de.yvert.jingle.ImageType;
import de.yvert.jingle.ldr.LdrImage2D;

public class AWTImageWriter
{

final String extension;
final ImageWriter imageWriter;

public AWTImageWriter(String extension)
{
	this.extension = extension;
	this.imageWriter = ImageIO.getImageWritersByFormatName(extension).next();
}

public String getExtension()
{ return extension; }

public ImageType[] supportedTypes()
{ return new ImageType[] { ImageType.RGBA_2D_BYTE }; }

public void write(Image in, OutputStream out) throws IOException
{
	LdrImage2D image = (LdrImage2D) in;
	imageWriter.setOutput(ImageIO.createImageOutputStream(out));
	
	int width = image.getWidth();
	int height = image.getHeight();
	
	BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
	
	int[] data = new int[width*height];
	image.encodeARGBint(data);
	bimg.setRGB(0, 0, width, height, data, 0, width);
	
	imageWriter.write(bimg);
}

}
